package com.workflow.engine.eb.steps.jd.login;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.workflow.engine.core.flow.StepState;
import com.workflow.engine.parser.constant.HttpMethod;
import com.workflow.engine.parser.flow.impl.AbstractStep;
import com.workflow.engine.parser.utils.JsoupHelper;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import static com.workflow.engine.parser.constant.HttpMethod.GET;
import static com.workflow.engine.parser.utils.StepStateUtil.successfulStepState;

/**
 * Created by Administrator on 2017/6/7.
 */
public class JDLoginIndex extends AbstractStep {

    private static final Logger logger = LoggerFactory.getLogger(JDLoginIndex.class);

    @Override
    public Logger getLogger() {
        return logger;
    }

    @Override
    protected String getRequestUrl() {
        return "https://passport.jd.com/new/login.aspx";
    }

    @Override
    protected HttpMethod getHttpMethod() {
        return GET;
    }

    @Override
    protected Map<String, String> getHeaders() {
        return new HashMap<String,String>(){{
            put("Host", "passport.jd.com");
            put("Connection", "keep-alive");
            put("Upgrade-Insecure-Requests", "1");
            put("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
            put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            put("Accept-Encoding", "gzip, deflate, sdch, br");
            put("Accept-Language", "zh-CN,zh;q=0.8");
        }};
    }

    @Override
    protected StepState handleResponse(Map<String, Object> context, Object response) throws Exception {
//        logger.info("首页：{}", response);
        Document doc = Jsoup.parse((String) response);
        String uuid = JsoupHelper.getStringById(doc, "uuid");
        //页面加载后初始值为空
        String eid = " WAZW25L5TSTRSK5QMV4PGVW3DH2C5HLDLCKWJD6VWO3K3UBMTBNLP7JWWF7LIOG76KQPDJKHPMBJLAG4KKF5DFHU6Q";
        //页面加载后初始值为空
        String fp = "  a17ead139fd7d7266e9dda98ec7feb53";
        String _t = JsoupHelper.getStringById(doc, "token");
        String loginType =  JsoupHelper.getStringById(doc, "loginType");
        //用户名
        String loginname = "";

        String nloginpwd = "dH0hKiFb+BHJkZ0rrJnwjwRTUPYlPMlbiuyQOFHm5wYy9Dyz2zMK8i3GTKask6VqfZhTKJJIRjCVYanpJn0PCBsFCvSk+JPRSkvnyTuFx/MKIBqJNaXKoDuI4N6v2sNKctk3b721DtUCzg5c1NfsjjaogPwJ6WyCTS296Ufhipk=";
        //记住我
        String chkRememberMe   ="";
        //验证码  默认不显示
        String authcode = "";
        //RSA加密公钥
        String pubKey = JsoupHelper.getStringById(doc, "pubKey");
        String sa_token = JsoupHelper.getStringById(doc, "sa_token");
        //页面加载后不存在
        String seqSid = "3375426000703533600";

        JSONObject jsonObject = JSON.parseObject(getLoginParams());
        

        context.put("uuid", jsonObject.get("uuid"));
        context.put("_t", jsonObject.get("_t"));
        context.put("eid", jsonObject.get("eid"));
        context.put("fp", jsonObject.get("fp"));
        context.put("loginType", jsonObject.get("loginType"));
        context.put("loginname", jsonObject.get("loginname"));
        context.put("nloginpwd", jsonObject.get("nloginpwd"));
        context.put("chkRememberMe", jsonObject.get("chkRememberMe"));
        context.put("authcode", jsonObject.get("authcode"));
        context.put("pubKey", jsonObject.get("pubKey"));
        context.put("sa_token", jsonObject.get("sa_token"));
        context.put("seqSid", jsonObject.get("seqSid"));

        //验证码地址
        String authCodeUrl = JsoupHelper.getAttributeByElementId(doc, "JD_Verification1", "src2");
        logger.info("验证码地址：{}", authCodeUrl);

        context.put("authCodeUrl", jsonObject.get("authCodeUrl"));

        return successfulStepState(this);
    }
    public static String getLoginParams() throws IOException {
        Runtime rt = Runtime.getRuntime();
        //phantomjs 和codes.js的路径之间有个空格 本代码只是测试用的绝对路径
        Process p = rt.exec("phantomjs /Users/houjinxin/Documents/phantomjs-2.1.1-macosx/examples/loadurlwithoutcss.js https://passport.jd.com/new/login.aspx --proxy=127.0.0.1:8888 --proxy-type=http --ignore-ssl-errors --ssl-protocol=tlsv1.2");
        InputStream is = p.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        StringBuffer sbf = new StringBuffer();
        String tmp = "";
        while((tmp = br.readLine())!=null){
            sbf.append(tmp);
        }
        System.out.println(sbf.toString());
        return sbf.toString();
    }

}
